<template>
  <div class="register-container">
    <h2 class="font-bold text-3xl text-gray-800 mt-5">注册</h2>
    <el-form ref="formRef" :rules="rules" :model="form" class="w-[300px]">
      <el-form-item prop="username">
        <el-input v-model="form.username" placeholder="请输入手机号" size="large" clearable />
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="form.password" type="password" autocomplete="off"
                  placeholder="请输入密码" show-password size="large" clearable />
      </el-form-item>
      <el-form-item prop="confirmPassword">
        <el-input v-model="form.confirmPassword" type="password" autocomplete="off"
                  placeholder="请确认密码" show-password size="large" clearable />
      </el-form-item>
      <el-form-item>
        <el-button round type="primary" @click="onSubmit" :loading="loading"
                   class="w-[300px] register-btn mt-4" size="large">
          注 册
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import { showMessage } from '@/composables/util';
import { registerUser } from '@/api/user/register';

const router = useRouter();

const form = reactive({
  username: '',
  password: '',
  confirmPassword: '',
});

const rules = {
  username: [
    { required: true, message: '手机号不能为空', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
  ],
};

const formRef = ref(null);
const loading = ref(false);

const onSubmit = () => {
  formRef.value.validate((valid) => {
    if (!valid) {
      console.log('验证不通过');
      return false;
    }
    if (form.password !== form.confirmPassword) {
      showMessage('两次输入的密码不一致', 'error');
      return;
    }
    // 调用注册 API
    registerUser({
      username: form.username,
      password: form.password,
    }).then(() => {
      showMessage('注册成功', 'success');
      router.push('/login');
    }).catch((error) => {
      showMessage('手机号格式不正确', 'error');
      console.error('注册失败:', error);
    });
  });
};
</script>

<style scoped>
.register-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  background-color: #f4f4f4;
}
</style> 